#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import string
import re
import xml.etree.ElementTree as etree
import ChannelConfigReader
import GameInfoReader

namespace = "http://schemas.android.com/apk/res/android"

#读取xml获得根节点
def read_xml(xml_file):
	tree = etree.parse(xml_file)
	return tree

def parse_attribute_name(attribute_name):
	ns = {
			'android:versionCode' : '{%s}versionCode' % namespace,
			'android:versionName' : '{%s}versionName' % namespace,
			'android:value' : '{%s}value' % namespace,
			'android:name' : '{%s}name' % namespace
		}
	return ns[attribute_name]


def run(src_xml, save_file, channelinfo , projectinfo):
	if( False == os.path.exists(src_xml) ):
		raise Exception(src_xml + "文件不存在，请检查!")
	if( False == os.path.exists(save_file) ):
		raise Exception(save_file + "文件不存在，请检查!")

	#注册xml命名空间android,否则写文件的时候会出现'ns'
	etree.register_namespace('android', namespace)
	
	#读取xml得到application节点
	tree = read_xml(src_xml)
	root = tree.getroot()
	
	if( len(channelinfo["packagename"])>0 ):
		root.set("package", channelinfo["packagename"])

	idx_code = parse_attribute_name('android:versionCode')
	root.set(idx_code, projectinfo.getOneProjectInfo("versionCode"))

	idx_name = parse_attribute_name('android:versionName')
	root.set(idx_name, projectinfo.getOneProjectInfo("versionName"))

	for elem in root.findall('application/meta-data'):
		att = elem.get("{%s}name" % namespace)
		if att == "UMENG_CHANNEL":
			elem.set('{%s}value'% namespace, channelinfo["umeng_channel"])
		elif att == "L_CHANNEL":
			elem.set('{%s}value'% namespace, channelinfo["l_channel"])
		elif att == "L_APPID":
			elem.set('{%s}value'% namespace, channelinfo["l_appid"])
		elif att == "EGAME_CHANNEL":
			elem.set('{%s}value'% namespace, channelinfo["egame_channel"])
		elif att == "wxappid":
			elem.set('{%s}value'% namespace, channelinfo["wxappid"])
		elif att == "wxappsecret":
			elem.set('{%s}value'% namespace, channelinfo["wxappsecret"])
		elif att == "SOULGAME_APPKEY":
			elem.set('{%s}value'% namespace, projectinfo.getOneProjectInfo("soulgame_appkey"))
		elif att == "SOULGAME_CHANNEL":
			elem.set('{%s}value'% namespace, channelinfo["soulgame_channel"])
		elif att == "dksdk_channel":
			elem.set('{%s}value'% namespace, channelinfo["dksdk_channel"])
		elif att == "PS_WXLOGIN":
			elem.set('{%s}value'% namespace, channelinfo["wxlogin"])

	for elem in root.findall('application/activity'):
		att = elem.get("{%s}name" % namespace)
		if( att.endswith("wxapi.WXEntryActivity") and len(channelinfo["packagename"])>0 ):
			elem.set('{%s}name'% namespace, channelinfo["packagename"] + ".wxapi.WXEntryActivity")
		
	tree.write(save_file, "utf-8")

#删除游戏工程本身入口Activity的Main和LAUNCHER
def delGameMain(src_xml, save_file):
	if( False == os.path.exists(src_xml) ):
		raise Exception(src_xml + "文件不存在，请检查!")
	
	etree.register_namespace('android', namespace)
	tree = read_xml(src_xml)
	root = tree.getroot()

	for elem in root.findall('application/activity/intent-filter/action'):
		att = elem.get("{%s}name" % namespace)
		if (att.endswith("android.intent.action.MAIN")):
			elem.set('{%s}name'% namespace, "soulgame.MAIN")
	for elem in root.findall('application/activity/intent-filter/category'):
		att = elem.get("{%s}name" % namespace)
		if (att.endswith("android.intent.category.LAUNCHER")):
			elem.set('{%s}name'% namespace, "android.intent.category.DEFAULT")

	tree.write(save_file, "utf-8")


if __name__=="__main__":
	projectconfigRd = GameInfoReader.GameInfoReader("./userconfig/gameinfo.conf")
	channelconfigRd = ChannelConfigReader.ChannelConfigReader("./userconfig/channelinfolist.conf")
	
	app_original_path = projectconfigRd.getOneProjectInfo("app_original_path")
	app_copy_path = projectconfigRd.getOneProjectInfo("app_copy_path")
	srcManifestFile = app_original_path + "/AndroidManifest.xml"
	desManifestFile = app_copy_path + "/AndroidManifest.xml"

	channelsdict = channelconfigRd.getConfigDict()
	for channelname in channelsdict:
		channelinfo = channelsdict[channelname].getChannelInfo()
		
		#更新AndroidManifest.xml：电信配置(lovegameid)、插件配置(l_appid、l_channel)、友盟渠道(umengchannel)
		run(desManifestFile,desManifestFile,channelinfo,projectconfigRd)
	
	
	
	
	
	
	